//
//  ChatViewController+Delegate.swift
//  EyeVisionForDoctors
//
//  Created by PMC on 2020/2/17.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON

extension ChatViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        let contentHeight = textView.contentSize.height
        guard contentHeight < kChatBarTextViewMaxHeight else { return }
        chatBarView.inputTextViewCurrentHeight = contentHeight + 17
        controlExpandableInputView(showExpandable: true)
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            sendTextMsg()
            return false
        }
        return true
    }
    
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        // 使 UITextView 滚动到末尾的区域
        UIView.setAnimationsEnabled(false)
        let range = NSMakeRange(textView.text.count - 1, 1)
        textView.scrollRangeToVisible(range)
        UIView.setAnimationsEnabled(true)
        return true
    }
}

extension ChatViewController: ChatBarViewDelegate, ChatRecordViewDelegate {
    func chatBarView(didSendImage barView: ChatBarView) {
        showBottomAlert()
    }
    
    func chatBarView(didSendVideoPhone barView: ChatBarView) {
        AlertTool.showAlert(self, message: "开启视频失败，目前视频仅能够由医生发起")
    }
    
    func chatRecordViewSend(model: UploadAudioModel) {
        sendAudioMsg(model)
    }
}

// MARK: - Delegate
extension ChatViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            YSGImageUpload.upload(image: image, imageType: .chat) { code, model, error in
                switch code {
                case .success:
                    guard let model = model else {
                        HUDTool.showError(message: "图片上传失败")
                        return
                    }
                    self.sendImageMsg(model)
                case .failure:
                    HUDTool.showError(message: error)
                }
            }
        }
        self.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
}

// MARK: - UITableViewDataSource
extension ChatViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let vm = viewModel else { return 0 }
        return vm.numberOfRows
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let vm = viewModel?.viewModel(fro: indexPath) else { return ChatBaseCell() }
        switch vm.messageType {
        case .unstart:
            let cell = tableView.dequeueReusableCell(withIdentifier: YSGAdvistoryUnstartCell.reuseIdentifier(),
                                                     for: indexPath) as! YSGAdvistoryUnstartCell
            cell.configure(with: vm.sendTime)
            return cell
        case .start:
            let cell = tableView.dequeueReusableCell(withIdentifier: YSGAdvisoryStartAndEndCell.reuseIdentifier(),
                                                     for: indexPath) as! YSGAdvisoryStartAndEndCell
            cell.configure(with: vm.sendTime, start: true)
            return cell
        case .text:
            let cell = tableView.dequeueReusableCell(withIdentifier: ChatTextCell.reuseIdentifier(), for: indexPath) as! ChatTextCell
            cell.configure(with: vm, detailVm: detailVM)
            return cell
        case .voice:
            let cell = tableView.dequeueReusableCell(withIdentifier: ChatRecordCell.reuseIdentifier(), for: indexPath) as! ChatRecordCell
            cell.configure(with: vm, detailVm: detailVM)
            cell.delegate = self
            return cell
        case .image:
            let cell = tableView.dequeueReusableCell(withIdentifier: ChatImageCell.reuseIdentifier(), for: indexPath) as! ChatImageCell
            cell.configure(with: vm, detailVm: detailVM)
            cell.delegate = self
            return cell
        case .prescription:
            let cell = tableView.dequeueReusableCell(withIdentifier: ChatPrescriptionCell.reuseIdentifier(), for: indexPath) as! ChatPrescriptionCell
            cell.delegate = self
            cell.configure(with: vm)
            return cell
        case .end:
            let cell = tableView.dequeueReusableCell(withIdentifier: YSGAdvisoryStartAndEndCell.reuseIdentifier(),
                                                     for: indexPath) as! YSGAdvisoryStartAndEndCell
            cell.configure(with: vm.sendTime, start: false)
            return cell
        default: return ChatBaseCell()
        }
    }
}

// MARK: - UITableViewDelegate
extension ChatViewController: UITableViewDelegate, UIScrollViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard let vm = viewModel?.viewModel(fro: indexPath) else { return 0 }
        return vm.cellHeight
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let vm = viewModel?.viewModel(fro: indexPath) else { return }
        
        switch vm.messageType {
        case .prescription:
            let vc = PrescriptionOrderDetailController(orderId: vm.prescriptionDetailVm.orderId)
            navigationController?.pushViewController(vc, animated: true)
        default: break
        }
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
}

// MARK: - cell delegate
extension ChatViewController: ChatPrescriptionCellDelegate, YSGChatCellDelegate {
    func didTappedPay(_ cell: ChatPrescriptionCell) {
        guard let indexPath = tableView.indexPath(for: cell),
            let vm = viewModel?.viewModel(fro: indexPath) else { return }
        pushDrugsOrderPayVc(vm)
    }
    
    private func pushDrugsOrderPayVc(_ vm: ChatMsgViewModel) {
        let orderPayVc = PrescriptionOrderPayController(orderId: vm.prescriptionDetailVm.orderId)
        navigationController?.pushViewController(orderPayVc, animated: true)
        orderPayVc.handlerClosure = { [weak self] in
            guard let self = self else { return }
            self.refreshChatRecord()
        }
    }
    
    func chatCell(didTappedAvatar cell: ChatBaseCell) {
        return
//        pushDoctorDetail()
    }
    
    func chatCell(_ cell: ChatBaseCell, didTappedImage vm: ChatMsgViewModel) {
        let brows = JSImagBrows(parentController: self,
                                images: [vm.src],
                                andCurrentIndex: 0,
                                andPlaceHolderImage: nil)
        brows?.modalPresentationStyle = .fullScreen
        brows?.show()
    }
    
    func chatRccordCellPlay(cell: ChatRecordCell) {
        guard let indexPath = tableView.indexPath(for: cell), let vm = viewModel, let msgVm = viewModel?.viewModel(fro: indexPath) else { return }
        let manager = RecordManager.sharedInstance
        //即将播放的和正在播放的是同一条语音，则暂停，否则暂停并继续播放另一条
        if let playing = manager.player?.isPlaying, playing {
            if manager.playingUrl == msgVm.msgContent {
                manager.stopPlay()
                print("同一条，暂停")
                return
            } else {
                manager.stopPlay()
                print("不是同一条，暂停并播放另一条")
            }
        }
        vm.playingIndexPath = vm.numberOfRows - indexPath.row
        viewModel = vm
        manager.play(urlStr: msgVm.msgContent)
    }
    
    private func pushDoctorDetail() {
        guard let vm = detailVM else { return }
        let detailVc = DoctorDetailController(with: vm.chatReceiveId)
        navigationController?.pushViewController(detailVc, animated: true)
    }
}
